package com.qianli.cashmama.trade.integration.audit.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.utils.StringUtils;
import com.qianli.cashmama.trade.common.utils.HttpUtil;
import com.qianli.cashmama.trade.common.utils.TradeConfigUtil;
import com.qianli.cashmama.trade.integration.audit.AuditIntegrationService;
import com.qianli.cashmama.trade.integration.audit.dto.AuditOrderInfoResponseDto;
import com.qianli.cashmama.trade.integration.audit.dto.TradeAuditDto;
import com.qianli.cashmama.trade.integration.audit.dto.TradeAuditParamDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2017/7/23
 * Time: 下午9:20
 */
@Service
public class AuditIntegrationServiceImpl implements AuditIntegrationService {
    private static final Logger logger = LoggerFactory.getLogger(AuditIntegrationServiceImpl.class);


    @Autowired
    private TradeConfigUtil tradeConfigUtil;

    @Override
    public boolean pushTradeToAudit(TradeAuditDto tradeAuditDto) {
        String taskSwitch = tradeConfigUtil.audit_push_switch();
        if (StringUtils.isEmpty(taskSwitch) || taskSwitch.equals("0")) {
            logger.info("== 推送给信审开关关闭 ==");
            return false;
        }

        return httpPushToAudit(tradeAuditDto);
    }

    /**
     * 打款成功后 通知信审（二次信审）
     *
     * @param tradeAuditDto
     * @return
     */
    @Override
    public boolean pushTradePayCallbackToAudit(TradeAuditDto tradeAuditDto) {
        String taskSwitch = tradeConfigUtil.audit_push_switch();
        if (StringUtils.isEmpty(taskSwitch) || taskSwitch.equals("0")) {
            logger.info("== 推送给信审开关关闭 ==");
            return false;
        }
        try {
            TradeAuditParamDto tradeAuditParamDto = new TradeAuditParamDto()
                    .setTradeNo(tradeAuditDto.getTradeNo())
                    .setRealCapital(tradeAuditDto.getBorrowTotalCapital().toString())
                    .setCapital(tradeAuditDto.getReceivedTotalCapital().toString())
                    .setChannelCode(tradeAuditDto.getChannelCode())
                    .setIdentityNo(tradeAuditDto.getIdentityNo())
                    .setIsNewAdd(tradeAuditDto.isNewAdd() ? 0 : 1)
                    .setMobile(tradeAuditDto.getMobile())
                    .setName(tradeAuditDto.getName())
                    .setProductCode(tradeAuditDto.getProductCode())
                    .setProductType(tradeAuditDto.getProductCategory())
                    .setUserCode(tradeAuditDto.getUserCode());

            List<TradeAuditParamDto> list = Arrays.asList(tradeAuditParamDto);

            String adminUrl = tradeConfigUtil.getAuditApiUrl();
            String pushTradeToAuditApi = adminUrl + "audit/trade/receiveTradePush2";

            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");

            String requestBody = JSON.toJSONString(list);
            logger.info("pushTradePayCallbackToAudit-开始推送给信审,requestBody[{}]", requestBody);

            String response = HttpUtil.postPageBody(pushTradeToAuditApi, headers, requestBody);
            logger.info("pushTradePayCallbackToAudit-推送给信审结束-pushTradeToAuditApi[{}],response:[{}]", pushTradeToAuditApi, JSON.toJSONString(response));

            JSONObject responseObject = JSON.parseObject(response);
            if (responseObject != null && Objects.equals(new Integer(0), responseObject.getInteger("code"))) {
                logger.info("pushTradePayCallbackToAudit-成功");
                return true;
            } else {
                logger.error("pushTradePayCallbackToAudit-异常-pushTradeToAuditApi[{}],response:[{}]", pushTradeToAuditApi, JSON.toJSONString(response));
                return false;
            }
        } catch (Exception e) {
            logger.error("pushTradePayCallbackToAudit-推送给信审失败,tradeAuditDto:[{}]", JSON.toJSONString(tradeAuditDto), e);
            return false;
        }
    }

    /**
     * highmark处理成功通知信审
     *
     * @param tradeNo
     * @return
     */
    @Override
    public boolean pushHighmarkToAudit(String tradeNo) {
        String taskSwitch = tradeConfigUtil.audit_push_switch();
        if (StringUtils.isEmpty(taskSwitch) || taskSwitch.equals("0")) {
            logger.info("== 推送给信审开关关闭 ==");
            return false;
        }
        try {
            String adminUrl = tradeConfigUtil.getAuditApiUrl();
            String pushTradeToAuditApi = adminUrl + "audit/highmark/pass";

            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");

            Map<String, Object> request = new HashMap<>();
            request.put("tradeNo", tradeNo);

            String requestBody = JSON.toJSONString(request);
            logger.info("pushHighmarkToAudit,开始推送给信审,requestBody:{}", requestBody);

            String response = HttpUtil.postPageBody(pushTradeToAuditApi, headers, requestBody);
            logger.info("pushHighmarkToAudit,推送给信审结束,response:{}", response);

            JSONObject responseObject = JSON.parseObject(response);
            if (responseObject != null && responseObject.getInteger("code") == 0) {
                return true;
            } else {
                logger.error("pushHighmarkToAudit,highmark通知信审失败,requestBody:{},response:{}", requestBody, response);
                return false;
            }
        } catch (Exception e) {
            logger.error("pushHighmarkToAudit,推送给信审异常,tradeAuditDto:[{}]", tradeNo, e);
            return false;
        }
    }

    private boolean httpPushToAudit(TradeAuditDto tradeAuditDto) {
        try {
            TradeAuditParamDto tradeAuditParamDto = new TradeAuditParamDto()
                    .setTradeNo(tradeAuditDto.getTradeNo())
                    .setRealCapital(tradeAuditDto.getBorrowTotalCapital().toString())
                    .setCapital(tradeAuditDto.getReceivedTotalCapital().toString())
                    .setChannelCode(tradeAuditDto.getChannelCode())
                    .setIdentityNo(tradeAuditDto.getIdentityNo())
                    .setIsNewAdd(tradeAuditDto.isNewAdd() ? 0 : 1)
                    .setMobile(tradeAuditDto.getMobile())
                    .setName(tradeAuditDto.getName())
                    .setProductCode(tradeAuditDto.getProductCode())
                    .setProductType(tradeAuditDto.getProductCategory())
                    .setUserCode(tradeAuditDto.getUserCode());

            List<TradeAuditParamDto> list = Arrays.asList(tradeAuditParamDto);

            String adminUrl = tradeConfigUtil.getAuditApiUrl();
            String pushTradeToAuditApi = adminUrl + "audit/trade/receiveTradePush";

            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");

            String requestBody = JSON.toJSONString(list);
            logger.info("pushTradeToAudit-开始推送给信审,requestBody[{}]", requestBody);

            String response = HttpUtil.postPageBody(pushTradeToAuditApi, headers, requestBody);
            logger.info("pushTradeToAudit-推送给信审结束-pushTradeToAuditApi[{}],response:[{}]", pushTradeToAuditApi, JSON.toJSONString(response));

            JSONObject responseObject = JSON.parseObject(response);
            if (responseObject != null && Objects.equals(new Integer(0), responseObject.getInteger("code"))) {
                logger.info("pushTradeToAudit-成功");
                return true;
            } else {
                logger.error("pushTradeToAudit-异常-pushTradeToAuditApi[{}],response:[{}]", pushTradeToAuditApi, JSON.toJSONString(response));
                return false;
            }
        } catch (Exception e) {
            logger.error("==HTTP==推送给信审失败==tradeAuditDto:[{}]", JSON.toJSONString(tradeAuditDto), e);
            return false;
        }
    }

    @Override
    public AuditOrderInfoResponseDto queryAuditOrderInfo(String tradeNo) {
        try {
            String adminUrl = tradeConfigUtil.getAuditApiUrl();
            String getAuditOrderInfoApi = adminUrl + "audit/verifiedOrderInfo/query";

            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");

            String requestBody = JSON.toJSONString(tradeNo);
            logger.info("getAuditOrderInfoVoResponse-开始,requestBody[{}]", requestBody);

            String response = HttpUtil.postPageBody(getAuditOrderInfoApi, headers, requestBody);
            logger.info("getAuditOrderInfoVoResponse-结束-getAuditOrderInfoApi[{}],response:[{}]", getAuditOrderInfoApi, JSON.toJSONString(response));

            JSONObject responseObject = JSON.parseObject(response);
            if (responseObject != null && Objects.equals(new Integer(0), responseObject.getInteger("code"))) {
                logger.info("getAuditOrderInfoVoResponse-成功");
                return JSON.toJavaObject(responseObject.getJSONObject("data"), AuditOrderInfoResponseDto.class);
            } else {
                logger.error("getAuditOrderInfoVoResponse-异常-getAuditOrderInfoApi[{}],response:[{}]", getAuditOrderInfoApi, JSON.toJSONString(response));
                return null;
            }
        } catch (Exception e) {
            logger.error("HTTP查询queryAuditOrderInfo失败,tradeNo:[{}]", tradeNo, e);
            return null;
        }
    }

    @Override
    public String getPinCode(String city, String pinCode) {
        try {
            String adminUrl =tradeConfigUtil.getAuditApiUrl();
            String getPinCodeInfoApi = adminUrl + "audit/pincode/query/" + pinCode + "";

            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");

            String requestBody = JSON.toJSONString(city);
            logger.info("getPinCode-开始查询pinCode,requestBody[{}]", requestBody);

            String response = HttpUtil.postPageBody(getPinCodeInfoApi, headers, requestBody);
            logger.info("getPinCode-查询pinCode结束-getPinCodeInfoApi[{}],response:[{}]", getPinCodeInfoApi, JSON.toJSONString(response));

            JSONObject responseObject = JSON.parseObject(response);
            if (responseObject != null && Objects.equals(new Integer(0), responseObject.getInteger("code"))) {
                logger.info("getPinCode-成功");
                return responseObject.getString("pincode");
            } else {
                logger.error("getPinCode-异常-getPinCodeInfoApi[{}],response:[{}]", getPinCodeInfoApi, JSON.toJSONString(response));
                return null;
            }
        } catch (Exception e) {
            logger.error("HTTP查询queryAuditOrderInfo失败,city:[{}],pinCode:[{}]", city, pinCode, e);
            return null;
        }
    }
}
